package com.yunhe.inspect.service.impl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.stuxuhai.jpinyin.PinyinException;
import com.yunhe.common.constant.InSpectConsts;
import com.yunhe.common.exception.ArgumentErrorException;
import com.yunhe.common.filter.ServerContextHolder;
import com.yunhe.common.model.ResultObject;
import com.yunhe.common.model.authority.Organization;
import com.yunhe.common.model.mybatis.PageResult;
import com.yunhe.common.util.CollectionUtil;
import com.yunhe.common.util.DateTimeUtils;
import com.yunhe.common.util.StringUtil;
import com.yunhe.inspect.client.AuthorityClient;
import com.yunhe.inspect.domain.*;
import com.yunhe.inspect.model.*;
import com.yunhe.inspect.repository.*;
import com.yunhe.inspect.service.DataInspectOrderService;
import com.yunhe.inspect.service.SerialNumService;
import com.yunhe.inspect.util.MyHeaderUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @description 巡检工单表
 * @author misty
 * @date 2021-11-10
 */
@Service
public class DataInspectOrderServiceImpl implements DataInspectOrderService {

    @Autowired
    private DataInspectOrderRepository dataInspectOrderRepository;

    @Autowired
    private DataInspectOrderItemRepository dataInspectOrderItemRepository;

    @Autowired
    private SerialNumService serialNumService;

    @Autowired
    private MyHeaderUtil myHeaderUtil;

    @Autowired
    private AuthorityClient authorityClient;

    @Autowired
    private InspectProcessRepository inspectProcessRepository;

    @Autowired
    private RectificationSheetRepository rectificationSheetRepository;


    @Override
    public int createDataInspectOrder (DataInspectOrder dataInspectOrder) {
        return dataInspectOrderRepository.createDataInspectOrderSelective(dataInspectOrder);
    }


    @Override
    public int deleteDataInspectOrder(int id) {
        return dataInspectOrderRepository.deleteDataInspectOrderByPrimaryKey(id);
    }


    @Override
    public int updateDataInspectOrder(DataInspectOrder dataInspectOrder) {
        return dataInspectOrderRepository.updateDataInspectOrderByPrimaryKeySelective(dataInspectOrder);
    }


    @Override
    public DataInspectOrderDetailVo findDataInspectOrderById(int id) {
        DataInspectOrderDetailVo dataInspectOrderDetailVo = new DataInspectOrderDetailVo();
        DataInspectOrder dataInspectOrder = dataInspectOrderRepository.searchDataInspectOrderByPrimaryKey(id);
        if(dataInspectOrder != null){
            BeanUtils.copyProperties(dataInspectOrder,dataInspectOrderDetailVo);
            //查询工单对应的检查项目信息
            List<InspectOrderItem> inspectOrderItems = dataInspectOrderItemRepository.searchDataInspectOrderItemByOrderId(id);
            if(CollectionUtil.isNotEmpty(inspectOrderItems)){
                dataInspectOrderDetailVo.setInspectOrderItemList(inspectOrderItems);
            }
            if (StringUtils.isNotEmpty(dataInspectOrder.getInspectedPersonSignature())){
                dataInspectOrderDetailVo.setInspectedPersonSignature(dataInspectOrder.getInspectedPersonSignature());
            }
            //todo 记录巡检工单流程
            InspectProcess orderProcess = inspectProcessRepository.getReviewProcessByOrderId(id);
            if (orderProcess != null){
                if (orderProcess.getRectificationId() != null){
                    RectificationSheet rectificationSheet = rectificationSheetRepository.searchRectificationSheetByPrimaryKey(orderProcess.getRectificationId());
                    dataInspectOrderDetailVo.setExistProblem(rectificationSheet.getHiddenDanger());
                    dataInspectOrderDetailVo.setRectificationDeadline(rectificationSheet.getRectificationDeadline());
                }
            }
            List<InspectProcess> processHistory = inspectProcessRepository.getProcessHistoryByInspectOrderId(id);
            dataInspectOrderDetailVo.setProcessHistory(processHistory);
            //如果为待复审工单，返回整改存在的问题和整改截至日期
            if (InSpectConsts.Inspect_Status.ToBeReview.value().equals(dataInspectOrder.getInspectStatus())){
                RectificationSheet latestRectificationSheet = rectificationSheetRepository.getLatestRectificationSheetByInspectOrderId(id);
                dataInspectOrderDetailVo.setExistProblem(latestRectificationSheet.getHiddenDanger());
                dataInspectOrderDetailVo.setRectificationDeadline(latestRectificationSheet.getRectificationDeadline());
            }
        }
        return dataInspectOrderDetailVo;
    }

    @Override
    public DataInspectOrderForWechatDTO findDataInspectOrderByIdForWechat(int id) {

        DataInspectOrderForWechatDTO dataInspectOrderByIdForWechat = dataInspectOrderRepository.findDataInspectOrderByIdForWechat(id);
        if (dataInspectOrderByIdForWechat != null) {
            //查询工单流程
            InspectProcess reviewProcess =
                    inspectProcessRepository.getLatestProcessByOrderId(dataInspectOrderByIdForWechat.getId());
            dataInspectOrderByIdForWechat.setInspectProcess(reviewProcess);
            //查询工单开局的整改单
            RectificationSheet rectificationSheet =
                    rectificationSheetRepository.getLatestRectificationSheetByInspectOrderId(dataInspectOrderByIdForWechat.getId());
            if (rectificationSheet != null) {
                rectificationSheet.setRectificationDeadline(rectificationSheet.getRectificationDeadline());
                dataInspectOrderByIdForWechat.setRectificationSheet(rectificationSheet);
            }

            //还需要更新工单的查看状态(只有已完成的巡检单才更新)
            if (InSpectConsts.Inspect_Status.Finish.value().equals(dataInspectOrderByIdForWechat.getInspectStatus())) {
                DataInspectOrder readerDataInspectOrder = dataInspectOrderRepository.searchDataInspectOrderByPrimaryKey(dataInspectOrderByIdForWechat.getId());
                readerDataInspectOrder.setWhetherToCheck(true);
                dataInspectOrderRepository.updateDataInspectOrderByPrimaryKeySelective(readerDataInspectOrder);
            }

            //查询整改的题目
            List<InspectOrderItem> inspectOrderItems = dataInspectOrderItemRepository.searchDataInspectOrderItemByOrderId(id);
            List<DataInspectOrderItem> dataInspectOrderItems = new ArrayList<>();
            for (InspectOrderItem inspectOrderItem : inspectOrderItems) {
                DataInspectOrderItem dataInspectOrderItem = new DataInspectOrderItem();
                dataInspectOrderItem.setItemPlanId(inspectOrderItem.getId());
                dataInspectOrderItem.setInspectOrderId(id);
                dataInspectOrderItem.setItemContent(inspectOrderItem.getItemContent());
                dataInspectOrderItem.setItemType(inspectOrderItem.getItemType());
                dataInspectOrderItem.setItemValue(inspectOrderItem.getItemValue());
                dataInspectOrderItems.add(dataInspectOrderItem);
            }
            dataInspectOrderByIdForWechat.setDataInspectOrderItemList(dataInspectOrderItems);
        }
        return dataInspectOrderByIdForWechat;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public  void batchDataInspectOrder(List<DataInspectOrder> dataLists) throws PinyinException {
        for (DataInspectOrder dataList : dataLists) {
            //String yq = PinyinHelper.getShortPinyin(dataList.getInspectOrderNo()).toUpperCase();
            //String office = PinyinHelper.getShortPinyin(dataList.getOfficeName()).toUpperCase();
            String xj = serialNumService.generateSerialNumberByModelCode("XJ");
            //yq+office+
            dataList.setInspectOrderNo(xj);
        }
        dataInspectOrderRepository.batchDataInspectOrder(dataLists);
        for (DataInspectOrder dataList : dataLists) {
            List<DataInspectOrderItem> dataInspectOrderItemList = dataList.getDataInspectOrderItemList();
            if(CollectionUtil.isNotEmpty(dataInspectOrderItemList)){
                for (DataInspectOrderItem dataInspectOrderItem : dataInspectOrderItemList) {
                    dataInspectOrderItem.setInspectOrderId(dataList.getId());
                }
                dataInspectOrderItemRepository.batchDataInspectOrderItem(dataInspectOrderItemList);
            }
        }
    }

    @Override
    public PageResult findDataInspectOrder(DataInspectOrderQueryCondition dataInspectOrderQueryCondition) throws ArgumentErrorException {
        PageResult result = null;
        Long headerUser = myHeaderUtil.getHeaderUser();
        if(headerUser == null){
            throw new ArgumentErrorException("用户登录信息已过期，请重新登录！");
        }
        String projectCode = ServerContextHolder.getContext().getProjectCode();
        if(StringUtil.isEmpty(projectCode)){
            throw new ArgumentErrorException("请选择项目查询巡检计划!");
        }
        dataInspectOrderQueryCondition.setStationId(Long.valueOf(projectCode));
        if(dataInspectOrderQueryCondition.getOrgId() == null){
            //查询当前登录人的部门以及负责部门和子部门
            ResponseEntity<ResultObject<List<Organization>>> responseEntity = authorityClient.getSubOrgByLoginUser(Long.valueOf(projectCode),headerUser,true);
            if(responseEntity != null){
                if(responseEntity.getStatusCode().is2xxSuccessful()){
                    List<Organization> organizations = responseEntity.getBody().getResults();
                    if(CollectionUtil.isNotEmpty(organizations)){
                        List<Long> orgIds = organizations.stream().map(Organization::getId).collect(Collectors.toList());
                        dataInspectOrderQueryCondition.setOrgIds(orgIds);
                    }
                }
            }
        }else {
            dataInspectOrderQueryCondition.setOrgIds(Arrays.asList(dataInspectOrderQueryCondition.getOrgId()));
        }
        PageHelper.startPage(dataInspectOrderQueryCondition.getPage(), dataInspectOrderQueryCondition.getSize());
        List<DataInspectOrderVo> dataInspectOrderVos = dataInspectOrderRepository.findDataInspectOrder(dataInspectOrderQueryCondition);
        PageInfo<DataInspectOrderVo> pageInfo = new PageInfo<>(dataInspectOrderVos);
        result = new PageResult(dataInspectOrderQueryCondition.getPage(), dataInspectOrderQueryCondition.getSize(), (int)pageInfo.getTotal(), dataInspectOrderVos);
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteDataInspectOrderByQueryCondition(DataInspectOrderQueryCondition dataInspectOrderQueryCondition) throws ArgumentErrorException {
        Long headerUser = myHeaderUtil.getHeaderUser();
        if(headerUser == null){
            throw new ArgumentErrorException("用户登录信息已过期，请重新登录！");
        }
        dataInspectOrderQueryCondition.setUpdator(headerUser);
        dataInspectOrderRepository.deleteDataInspectOrderByQueryCondition(dataInspectOrderQueryCondition);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteDataInspectOrderByIds(List<Integer> ids) throws ArgumentErrorException {
        Long headerUser = myHeaderUtil.getHeaderUser();
        if(headerUser == null){
            throw new ArgumentErrorException("用户登录信息已过期，请重新登录！");
        }
        dataInspectOrderRepository.deleteDataInspectOrderByIds(ids,headerUser);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void dealDataInspectOrder() {
        //查询未处理的巡检工单信息
        List<DataInspectOrder> dataInspectOrders = dataInspectOrderRepository.findDataInspectOrderByNoInspectOrderInspector();
        if(CollectionUtil.isNotEmpty(dataInspectOrders)){
            for (DataInspectOrder dataInspectOrder : dataInspectOrders) {
                //获取当前天的时间戳
                long nowDay = DateTimeUtils.asDate(LocalDate.now()).getTime();
                //过期时间的时间戳
                long expirationTime = DateTimeUtils.formatToDate(dataInspectOrder.getInspectOrderExpirationTime(), DateTimeUtils.PATTERN.DATE.value()).getTime();
                if(nowDay > expirationTime){
                    dataInspectOrder.setFormStatus(InSpectConsts.FormStatus.Beoverdue.value());
                    dataInspectOrderRepository.updateDataInspectOrderByPrimaryKeySelective(dataInspectOrder);
                }

            }
        }
    }

    @Override
    public PageResult getDataInspectOrderByConditionApp(InspectOrderAppCondition inspectOrderAppCondition) throws ArgumentErrorException {
        Long headerUser = myHeaderUtil.getHeaderUser();
        if (headerUser == null){
            throw new ArgumentErrorException("用户信息已过期，请重新登录！");
        }
        inspectOrderAppCondition.setInspector(headerUser);
        //时间格式转换
        if (StringUtils.isNotEmpty(inspectOrderAppCondition.getReviewStartTime())){
            inspectOrderAppCondition.setReviewStartTime(inspectOrderAppCondition.getReviewStartTime() + " 00:00:00");
        }
        if (StringUtils.isNotEmpty(inspectOrderAppCondition.getReviewEndTime())){
            inspectOrderAppCondition.setReviewEndTime(inspectOrderAppCondition.getReviewEndTime() + " 23:59:59");
        }
        if (StringUtils.isNotEmpty(inspectOrderAppCondition.getInspectOrderExpirationStartTime())){
            inspectOrderAppCondition.setInspectOrderExpirationStartTime(inspectOrderAppCondition.getInspectOrderExpirationStartTime() + " 00:00:00");
        }
        if (StringUtils.isNotEmpty(inspectOrderAppCondition.getInspectOrderExpirationEndTime())){
            inspectOrderAppCondition.setInspectOrderExpirationEndTime(inspectOrderAppCondition.getInspectOrderExpirationEndTime() + " 23:59:59");
        }
        String projectCode = ServerContextHolder.getContext().getProjectCode();
        if(StringUtil.isEmpty(projectCode)){
            throw new ArgumentErrorException("请选择项目查询巡检计划!");
        }
        inspectOrderAppCondition.setStationId(Long.valueOf(projectCode));
        PageResult result = null;
        PageHelper.startPage(inspectOrderAppCondition.getPage(), inspectOrderAppCondition.getSize());
        List<DataInspectOrder> dataInspectOrderByConditionApp = dataInspectOrderRepository.getDataInspectOrderByConditionApp(inspectOrderAppCondition);
        for (DataInspectOrder inspectOrder : dataInspectOrderByConditionApp) {
            InspectProcess latestProcess = inspectProcessRepository.getReviewProcessByOrderId(inspectOrder.getId());
            if (latestProcess != null){
                inspectOrder.setContentUpdateFlag(latestProcess.isContentUpdateFlag());
            }
            RectificationSheet latestRectificationSheet = rectificationSheetRepository.getLatestRectificationSheetByInspectOrderId(inspectOrder.getId());
            if (latestRectificationSheet != null){
                if (StringUtils.isNotEmpty(latestRectificationSheet.getDeadlineStatus())){
                    inspectOrder.setDeadlineStatus(latestRectificationSheet.getDeadlineStatus());
                }
            }
        }
        PageInfo<DataInspectOrder> pageInfo = new PageInfo<>(dataInspectOrderByConditionApp);
        result = new PageResult(inspectOrderAppCondition.getPage(), inspectOrderAppCondition.getSize(), (int)pageInfo.getTotal(), dataInspectOrderByConditionApp);
        return result;
    }

    @Override
    public PageResult getDataInspectOrderByConditionForWechat(InspectOrderWechatCondition inspectOrderWechatCondition) throws ArgumentErrorException {
        if (inspectOrderWechatCondition.getCompanyId() == null) {
            throw new ArgumentErrorException("请选择企业！");
        }
        //做一个时间格式的转换
        if (StringUtils.isNotEmpty(inspectOrderWechatCondition.getInspectOrderExpirationStartTime())) {
            inspectOrderWechatCondition
                    .setInspectOrderExpirationStartTime(inspectOrderWechatCondition.getInspectOrderExpirationStartTime() + " 00:00:00");
        }
        if (StringUtils.isNotEmpty(inspectOrderWechatCondition.getInspectOrderExpirationEndTime())) {
            inspectOrderWechatCondition
                    .setInspectOrderExpirationEndTime(inspectOrderWechatCondition.getInspectOrderExpirationEndTime() + " 23:59:59");
        }
        if (StringUtils.isNotEmpty(inspectOrderWechatCondition.getReviewStartTime())) {
            inspectOrderWechatCondition
                    .setReviewStartTime(inspectOrderWechatCondition.getReviewStartTime() + " 00:00:00");
        }
        if (StringUtils.isNotEmpty(inspectOrderWechatCondition.getReviewEndTime())) {
            inspectOrderWechatCondition
                    .setReviewEndTime(inspectOrderWechatCondition.getReviewEndTime() + " 23:59:59");
        }

        PageResult result = null;
        PageHelper.startPage(inspectOrderWechatCondition.getPage(), inspectOrderWechatCondition.getSize());
        List<DataInspectOrder> dataInspectOrderByConditionForWechat = dataInspectOrderRepository.getDataInspectOrderByConditionForWechat(inspectOrderWechatCondition);
        PageInfo<DataInspectOrder> pageInfo = new PageInfo<>(dataInspectOrderByConditionForWechat);
        result = new PageResult(inspectOrderWechatCondition.getPage(), inspectOrderWechatCondition.getSize(), (int)pageInfo.getTotal(), dataInspectOrderByConditionForWechat);
        return result;
    }

    @Override
    public AppDetailVO findDataInspectOrderByIdApp(int inspectOrderId) {
        AppDetailVO appDetailVO = new AppDetailVO();
        DataInspectOrder inspectOrder = dataInspectOrderRepository.searchDataInspectOrderByPrimaryKey(inspectOrderId);
        List<InspectOrderItem> inspectOrderItems = dataInspectOrderItemRepository.searchDataInspectOrderItemByOrderId(inspectOrderId);
        List<DataInspectOrderItem> dataInspectOrderItems = new ArrayList<>();
        for (InspectOrderItem inspectOrderItem : inspectOrderItems) {
            DataInspectOrderItem dataInspectOrderItem = new DataInspectOrderItem();
            dataInspectOrderItem.setItemPlanId(inspectOrderItem.getId());
            dataInspectOrderItem.setInspectOrderId(inspectOrderId);
            dataInspectOrderItem.setItemContent(inspectOrderItem.getItemContent());
            dataInspectOrderItem.setItemType(inspectOrderItem.getItemType());
            if(StringUtils.isNotEmpty(inspectOrderItem.getItemValue())){
                dataInspectOrderItem.setItemValue(inspectOrderItem.getItemValue());
            }
            dataInspectOrderItems.add(dataInspectOrderItem);
        }
        inspectOrder.setDataInspectOrderItemList(dataInspectOrderItems);
        appDetailVO.setDataInspectOrder(inspectOrder);
        if (InSpectConsts.Inspect_Status.ToBeReview.value().equals(inspectOrder.getInspectStatus())){
            RectificationSheet latestRectificationSheet = rectificationSheetRepository.getLatestRectificationSheetByInspectOrderId(inspectOrderId);
            appDetailVO.setRectificationSheet(latestRectificationSheet);
        }
        return appDetailVO;
    }

    @Override
    public void judge(JudgeBO judgeBO) throws ArgumentErrorException {
        Long headerUser = myHeaderUtil.getHeaderUser();
        if (headerUser == null){
            throw new ArgumentErrorException("用户信息已过期，请重新登录！");
        }
        //保存评审流程
        InspectProcess judgeProcess = new InspectProcess();
        judgeProcess.setInspectOrderId(judgeBO.getInspectOrderId());
        judgeProcess.setProcessStatus(judgeBO.getTargetStatus());
        judgeProcess.setCreateTime(new Date());
        inspectProcessRepository.createInspectProcess(judgeProcess);
        //保存巡检项目选择的值
        List<DataInspectOrderItem> inspectItems = judgeBO.getInspectItems();
        for (DataInspectOrderItem submitInspectItem : inspectItems) {
            DataInspectOrderItem inspectOrderItem = dataInspectOrderItemRepository.getByInspectOrderIdAndItemPlanId(judgeBO.getInspectOrderId(), submitInspectItem.getItemPlanId());
            inspectOrderItem.setItemValue(submitInspectItem.getItemValue());
            dataInspectOrderItemRepository.updateDataInspectOrderItemByPrimaryKeySelective(inspectOrderItem);
        }
        //更新巡检单状态
        DataInspectOrder dataInspectOrder = dataInspectOrderRepository.searchDataInspectOrderByPrimaryKey(judgeBO.getInspectOrderId());
        dataInspectOrder.setInspectStatus(judgeBO.getTargetStatus());
        if (InSpectConsts.Inspect_Status.ToBeReview.value().equals(judgeBO.getTargetStatus())){
            dataInspectOrder.setAppOrder("5");
        }
        dataInspectOrder.setUpdator(headerUser);
        dataInspectOrder.setUpdateTime(new Date());
        dataInspectOrder.setInspectOrderInspector(headerUser);
        dataInspectOrder.setInspectedPersonSignature(judgeBO.getInspectedPersonSignature());
        if (InSpectConsts.Inspect_Status.Finish.value().equals(judgeBO.getTargetStatus())){
            //评审时如果直接完成，记录评审时间（整改单接收时间），如需整改，在开整改单时记录（更新）评审时间（整改单接收时间）
            dataInspectOrder.setJudgeTime(new Date());
            //评审时直接完成，将巡检单的表单状态更新为已完成（HasEnded）
            dataInspectOrder.setFormStatus(InSpectConsts.FormStatus.HasEnded.value());
        }
        dataInspectOrderRepository.updateDataInspectOrderByPrimaryKeySelective(dataInspectOrder);
    }

    @Override
    public void rectifyReform(RectifyReformBO rectifyReformBO) throws ParseException, ArgumentErrorException {
        Long headerUser = myHeaderUtil.getHeaderUser();
        if (headerUser == null){
            throw new ArgumentErrorException("用户信息已过期，请重新登录！");
        }
        //生成整改单
        RectificationSheet rectificationSheet = new RectificationSheet();
        rectificationSheet.setInspectOrderId(rectifyReformBO.getInspectOrderId());
        rectificationSheet.setHiddenDanger(rectifyReformBO.getHiddenDanger());
        rectificationSheet.setRectificationDeadline(rectifyReformBO.getRectificationDeadline());

        //2天到毫秒
        long twoDay = 2*24*60*60*1000;
        long timeDifference = DateTimeUtils.compareDateStr(DateTimeUtils.todayStr("yyyy-MM-dd"), new SimpleDateFormat("yyyy-MM-dd").format(rectifyReformBO.getRectificationDeadline()),"yyyy-MM-dd");
        //判断整改时间是否临近，当前时间与整改时间小于等于2天为即将到期
        if (timeDifference > twoDay) {
            //正常
            rectificationSheet.setDeadlineStatus(InSpectConsts.Rectification_Status.Normal.value());
        } else if (timeDifference >= 0) {
            //即将到期
            rectificationSheet.setDeadlineStatus(InSpectConsts.Rectification_Status.Expiring.value());
        } else {
            //超时
            rectificationSheet.setDeadlineStatus(InSpectConsts.Rectification_Status.TimedOut.value());
        }

        rectificationSheet.setCreateTime(new Date());
        rectificationSheetRepository.createRectificationSheet(rectificationSheet);
        //更新流程中的整改单id
        InspectProcess toBeReviewProcess = inspectProcessRepository.getReviewProcessByOrderId(rectifyReformBO.getInspectOrderId());
        toBeReviewProcess.setRectificationId(rectificationSheet.getId());
        inspectProcessRepository.updateInspectProcessByPrimaryKeySelective(toBeReviewProcess);
        //更新巡检单中的复审时间（整改截止日期）
        DataInspectOrder inspectOrder = dataInspectOrderRepository.searchDataInspectOrderByPrimaryKey(rectifyReformBO.getInspectOrderId());
        inspectOrder.setReviewTime(rectifyReformBO.getRectificationDeadline());
        int reviewRemainingDays = daysBetween(new Date(), rectifyReformBO.getRectificationDeadline());
        inspectOrder.setReviewRemainingDays(reviewRemainingDays);
        if (reviewRemainingDays <= 0){
            inspectOrder.setAppOrder("1");
        }else if (reviewRemainingDays <= 2){
            inspectOrder.setAppOrder("3");
        }else {
            inspectOrder.setAppOrder("5");
        }
        inspectOrder.setUpdator(headerUser);
        inspectOrder.setUpdateTime(new Date());
        //开具整改单时记录（更新）评审时间（整改单接收时间）
        inspectOrder.setJudgeTime(new Date());
        dataInspectOrderRepository.updateDataInspectOrderByPrimaryKeySelective(inspectOrder);
    }

    @Override
    public void review(ReviewBO reviewBO) throws ArgumentErrorException {
        Long headerUser = myHeaderUtil.getHeaderUser();
        if (headerUser == null){
            throw new ArgumentErrorException("用户信息已过期，请重新登录！");
        }
        //更新复审流程
        InspectProcess reviewProcess = inspectProcessRepository.getReviewProcessByOrderId(reviewBO.getInspectOrderId());
        reviewProcess.setReviewSuggestion(reviewBO.getReviewContent());
        reviewProcess.setProcessStatus(reviewBO.getTargetStatus());
        RectificationSheet rectificationSheet = rectificationSheetRepository.searchRectificationSheetByPrimaryKey(reviewProcess.getRectificationId());
        reviewProcess.setReviewTime(rectificationSheet.getRectificationDeadline());
        inspectProcessRepository.updateInspectProcessByPrimaryKeySelective(reviewProcess);

        if (InSpectConsts.Inspect_Status.ToBeReview.value().equals(reviewBO.getTargetStatus())){
            //复审不通过，生成新的流程
            InspectProcess nextReviewProcess = new InspectProcess();
            nextReviewProcess.setInspectOrderId(reviewBO.getInspectOrderId());
            nextReviewProcess.setProcessStatus(reviewBO.getTargetStatus());
            nextReviewProcess.setCreateTime(new Date());
            inspectProcessRepository.createInspectProcess(nextReviewProcess);
        }
        //更新巡检单状态
        DataInspectOrder inspectOrder = dataInspectOrderRepository.searchDataInspectOrderByPrimaryKey(reviewBO.getInspectOrderId());
        inspectOrder.setInspectStatus(reviewBO.getTargetStatus());
        inspectOrder.setUpdator(headerUser);
        inspectOrder.setUpdateTime(new Date());
        if(InSpectConsts.Inspect_Status.Finish.value().equals(reviewBO.getTargetStatus())){
            //复审完成时，将巡检单的表单状态更新为已完成（HasEnded）
            inspectOrder.setFormStatus(InSpectConsts.FormStatus.HasEnded.value());
        }
        dataInspectOrderRepository.updateDataInspectOrderByPrimaryKeySelective(inspectOrder);
    }

    @Override
    public void calculateRemainingDays() throws ParseException {
        List<DataInspectOrder> unFinishInspectOrders = dataInspectOrderRepository.getUnFinishInspectOrder();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        for (DataInspectOrder unFinishInspectOrder : unFinishInspectOrders) {
            if (unFinishInspectOrder.getInspectOrderExpirationTime() != null){
                Date expirationTime = sdf.parse(unFinishInspectOrder.getInspectOrderExpirationTime());
                int inspectRemainingDays = daysBetween(new Date(), expirationTime);
                unFinishInspectOrder.setInspectRemainingDays(inspectRemainingDays);
                //根据到期时间计算确定巡检单期限，临近3天到期的复审单为 1即将到期，大于3天为 0正常
                if (inspectRemainingDays > 3){
                    unFinishInspectOrder.setInspectDeadlineStatus("0");
                }else if (inspectRemainingDays <= 3 && inspectRemainingDays >= 0){
                    unFinishInspectOrder.setInspectDeadlineStatus("1");
                } if (inspectRemainingDays < 0){
                    unFinishInspectOrder.setInspectDeadlineStatus("2");
                }
            }
            if (unFinishInspectOrder.getReviewTime() != null){
                unFinishInspectOrder.setReviewRemainingDays(daysBetween(new Date(), unFinishInspectOrder.getReviewTime()));
            }
            dataInspectOrderRepository.updateDataInspectOrderByPrimaryKeySelective(unFinishInspectOrder);
        }
        for (DataInspectOrder unFinishInspectOrder : unFinishInspectOrders) {
            //App排序优先级
            if (InSpectConsts.Inspect_Status.ToBeReview.value().equals(unFinishInspectOrder.getInspectStatus())){
                //待复审
                if (unFinishInspectOrder.getReviewRemainingDays() != null){
                    if (unFinishInspectOrder.getReviewRemainingDays() <= 0){
                        //超时待复审
                        unFinishInspectOrder.setAppOrder("1");
                    }else if (unFinishInspectOrder.getReviewRemainingDays() <= 2){
                        //临近2天待复审
                        unFinishInspectOrder.setAppOrder("3");
                    }else {
                        //待复审（3天及以上）
                        unFinishInspectOrder.setAppOrder("5");
                    }
                }
            }else if (InSpectConsts.Inspect_Status.ToBeInspected.value().equals(unFinishInspectOrder.getInspectStatus())){
                //待巡检
                if (unFinishInspectOrder.getInspectRemainingDays() != null){
                    if (unFinishInspectOrder.getInspectRemainingDays() <= 3){
                        //临近3天待巡检
                        unFinishInspectOrder.setAppOrder("2");
                    } else {
                        //待巡检（4天及以上）
                        unFinishInspectOrder.setAppOrder("4");
                    }
                }

            }
            dataInspectOrderRepository.updateDataInspectOrderByPrimaryKeySelective(unFinishInspectOrder);
        }
    }

    @Override
    public void judgeRectifyReform(RectifyReformBO rectifyReformBO) throws ArgumentErrorException, ParseException {
        Long headerUser = myHeaderUtil.getHeaderUser();
        if (headerUser == null){
            throw new ArgumentErrorException("用户信息已过期，请重新登录！");
        }
        if ("01".equals(rectifyReformBO.getStatus())){
            //评审结束再开具整改单，直接完成的整改单不走此处的逻辑
            /**评审*/
            //保存评审流程
            InspectProcess judgeProcess = new InspectProcess();
            judgeProcess.setInspectOrderId(rectifyReformBO.getInspectOrderId());
            judgeProcess.setProcessStatus(InSpectConsts.Inspect_Status.ToBeReview.value());
            judgeProcess.setCreateTime(new Date());
            inspectProcessRepository.createInspectProcess(judgeProcess);
            //保存巡检项目选择的值
            List<DataInspectOrderItem> inspectItems = rectifyReformBO.getInspectItems();
            for (DataInspectOrderItem submitInspectItem : inspectItems) {
                DataInspectOrderItem inspectOrderItem = dataInspectOrderItemRepository.getByInspectOrderIdAndItemPlanId(rectifyReformBO.getInspectOrderId(), submitInspectItem.getItemPlanId());
                inspectOrderItem.setItemValue(submitInspectItem.getItemValue());
                dataInspectOrderItemRepository.updateDataInspectOrderItemByPrimaryKeySelective(inspectOrderItem);
            }
            //更新巡检单状态
            DataInspectOrder dataInspectOrder = dataInspectOrderRepository.searchDataInspectOrderByPrimaryKey(rectifyReformBO.getInspectOrderId());
            dataInspectOrder.setInspectStatus(InSpectConsts.Inspect_Status.ToBeReview.value());
            dataInspectOrder.setAppOrder("5");
            dataInspectOrder.setUpdator(headerUser);
            dataInspectOrder.setUpdateTime(new Date());
            dataInspectOrder.setInspectOrderInspector(headerUser);
            dataInspectOrder.setInspectedPersonSignature(rectifyReformBO.getInspectedPersonSignature());
            dataInspectOrderRepository.updateDataInspectOrderByPrimaryKeySelective(dataInspectOrder);
            /**开具整改单*/
            rectifyReform(rectifyReformBO);
        }else {
            //复审不合格后开具整改单，复审合格完成不走此处逻辑
            /**提交复审意见*/
            //更新复审流程
            InspectProcess reviewProcess = inspectProcessRepository.getReviewProcessByOrderId(rectifyReformBO.getInspectOrderId());
            reviewProcess.setReviewSuggestion(rectifyReformBO.getReviewContent());
            reviewProcess.setProcessStatus(InSpectConsts.Inspect_Status.ToBeReview.value());
            RectificationSheet rectificationSheet = rectificationSheetRepository.searchRectificationSheetByPrimaryKey(reviewProcess.getRectificationId());
            reviewProcess.setReviewTime(rectificationSheet.getRectificationDeadline());
            inspectProcessRepository.updateInspectProcessByPrimaryKeySelective(reviewProcess);
            //复审不通过，生成新的流程
            InspectProcess nextReviewProcess = new InspectProcess();
            nextReviewProcess.setInspectOrderId(rectifyReformBO.getInspectOrderId());
            nextReviewProcess.setProcessStatus(InSpectConsts.Inspect_Status.ToBeReview.value());
            nextReviewProcess.setCreateTime(new Date());
            inspectProcessRepository.createInspectProcess(nextReviewProcess);
            //更新巡检单状态
            DataInspectOrder inspectOrder = dataInspectOrderRepository.searchDataInspectOrderByPrimaryKey(rectifyReformBO.getInspectOrderId());
            inspectOrder.setInspectStatus(InSpectConsts.Inspect_Status.ToBeReview.value());
            inspectOrder.setUpdator(headerUser);
            inspectOrder.setUpdateTime(new Date());
            dataInspectOrderRepository.updateDataInspectOrderByPrimaryKeySelective(inspectOrder);
            /**开具整改单*/
            rectifyReform(rectifyReformBO);
        }
    }

    @Override
    public List<RectificationHistoryVO> getRectificationHistory(int inspectOrderId) {
        List<RectificationHistoryVO> rectificationHistoryVOList = new ArrayList<>();
        List<InspectProcess> processHistory = inspectProcessRepository.getProcessHistoryByInspectOrderId(inspectOrderId);
        for (InspectProcess process : processHistory) {
            RectificationHistoryVO rectificationHistoryVO = new RectificationHistoryVO();
            rectificationHistoryVO.setReviewTime(process.getReviewTime());
            rectificationHistoryVO.setReviewSuggestion(process.getReviewSuggestion());
            if (process.getRectificationId() != null) {
                RectificationSheet rectificationSheet = rectificationSheetRepository.searchRectificationSheetByPrimaryKey(process.getRectificationId());
                rectificationHistoryVO.setHiddenDanger(rectificationSheet.getHiddenDanger());
                rectificationHistoryVO.setRectificationContent(rectificationSheet.getRectificationContent());
                rectificationHistoryVO.setImages(rectificationSheet.getImages());
            }
            rectificationHistoryVOList.add(rectificationHistoryVO);
        }
        return rectificationHistoryVOList;
    }

    /**
     * 计算两个日期之间相差的天数
     * @param smdate 较小的时间
     * @param bdate  较大的时间
     * @return 相差天数
     * @throws ParseException
     */
    public static int daysBetween(Date smdate,Date bdate)
    {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        try {
            smdate=sdf.parse(sdf.format(smdate));
            bdate=sdf.parse(sdf.format(bdate));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Calendar cal = Calendar.getInstance();
        cal.setTime(smdate);
        long time1 = cal.getTimeInMillis();
        cal.setTime(bdate);
        long time2 = cal.getTimeInMillis();
        long between_days=(time2-time1)/(1000*3600*24);

        return Integer.parseInt(String.valueOf(between_days));
    }

    public static void main(String[] args) {
        System.out.println();
    }


}